package bidgetserver;

import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.util.List;
import javax.jdo.PersistenceManager;
import bidgetserver.Product;
import bidgetserver.PMF;

public class ShowProducts extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {

    	String userName = req.getParameter("userName");
    	
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	String response = "";
        
    	String query = "select from "+Product.class.getName()+" where author == '"+userName+"'";
        query += " && flag == true";
        List<Product> userProducts = (List<Product>) pm.newQuery(query).execute();
		
		if (userProducts.isEmpty()){
		} else {
			response = "{\"products\" : [";
			for (Product p : userProducts){
				response += " \""+p.getKey()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response+= " ], \"prices\" : [";
			for (Product p : userProducts){
				response += " \""+p.getPrice()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response+= " ], \"isbuy\" : [";
			for (Product p : userProducts){
				response += " \""+p.BuyOrSell()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response+= " ], \"timealert\" : [";
			for (Product p : userProducts){
				response += " \""+p.getTimeAlert()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response += " ],";
		}
		
		query = "select from "+Product.class.getName()+" where author == '"+userName+"'";
        query += " && flag == false";
        List<Product> userHistory = (List<Product>) pm.newQuery(query).execute();
		
		if (userHistory.isEmpty()){
			if(userProducts.isEmpty())
				resp.getWriter().print(response);
			else
				resp.getWriter().print(response+"}");
		} else {
			if(userProducts.isEmpty())
				response+="{";
			response += " \"history\" : [";
			for (Product p : userHistory){
				response += " \""+p.getKey()+"\",";
			}
			response = response.substring(0, response.length()-1);
			resp.getWriter().print(response+" ]}");
		}
		
    }
}
